package com.shujia.day15;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Code08ThreadTicketLock {
    public static void main(String[] args) {

        /*
            使用  ReentrantLock 锁的方式来完成对票数的控制

            ReentrantLock中存在有两个成员方法
                void lock()  加锁操作 对当前CPU的执行权限进行加锁
                void unlock()  解锁操作  释放执行权限


         */


        WindowLock window = new WindowLock();

        Thread thread1 = new Thread(window, "售票员1");
        Thread thread2 = new Thread(window, "售票员2");
        Thread thread3 = new Thread(window, "售票员3");

        thread1.start();
        thread2.start();
        thread3.start();

    }
}

class WindowLock implements Runnable {
    int ticket = 100;
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.lock();
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName()+"销售了一张票，还剩" + --ticket + "张表");
            }
            lock.unlock();
        }
    }
}